﻿using OpenQA.Selenium;
using Serilog;

namespace ToolApp.EdgeRewards;

public class Login
{
    public Login(EdgeRewardsBase sef, string userName, string password)
    {
        Log.Information("开始注销已登录帐号...");
        //注销rewards.bing
        sef.WebDriver!.Navigate().GoToUrl("https://rewards.bing.com/Signout");
        try
        {
            sef.WaitUntilUrl(["https://login.microsoftonline.com/consumers/oauth2/v2.0/logoutsession"], 20);
            //*[@id="initiator_redirect_link"]
            Thread.Sleep(TimeSpan.FromSeconds(5));
            var elements = sef.WebDriver.FindElements(By.Id("initiator_redirect_link"));
            if (elements.Count > 0)
            {
                elements[0].Click();
            }
        }
        catch (Exception)
        {
            // ignored
        }
        sef.WaitUntilUrl(["login.live.com", "rewards.bing.com/welcome"]);

        //检查cn.bing.com登录状态，并注销
        sef.WebDriver.Navigate().GoToUrl("https://cn.bing.com/");
        Thread.Sleep(1000);
        var btn = sef.WaitUntilClickable(By.Id("id_s"));
        if (btn.Text != "登录")
        {
            sef.WebDriver.FindElement(By.Id("id_l")).Click();
            sef.WebDriver.FindElement(By.XPath("//*[@id=\"id_d\"]/div/div[3]/a")).Click();
        }

        Log.Information("开始登录{0}，{1}", userName, "登录中请不要最小化浏览器，或其他应用全屏遮挡");
        sef.WebDriver.Navigate()
            .GoToUrl(
                "https://rewards.bing.com/createuser?userScenarioId=anonsignin&idru=https%3A%2F%2Frewards.bing.com");
        sef.WebDriver.FindElement(By.Id("i0116")).SendKeys(userName);
        sef.WebDriver.FindElement(By.Id("idSIButton9")).Click();
        sef.WebDriver.FindElement(By.Id("i0118")).SendKeys(password);
        sef.WebDriver.FindElement(By.Id("idSIButton9")).Click();
        var acceptButton = sef.WebDriver.FindElements(By.Id("acceptButton"));
        if (acceptButton.Count > 0)
        {
            acceptButton[0].Click();
        }

        sef.WaitUntilUrl(["https://rewards.bing.com/"]);
        sef.LastTotal = Convert.ToInt32(sef.WebDriver
            .FindElement(By.XPath("//*[@id=\"balanceToolTipDiv\"]/p/mee-rewards-counter-animation/span"))
            .Text.Replace(",", ""));
        Log.Information("登录成功，可用积分：{0}", sef.LastTotal);
    }

}